package cn.edu.scnu.springbootcinema.service;

import cn.edu.scnu.springbootcinema.entity.Actor;
import cn.edu.scnu.springbootcinema.entity.MovieActor;
import cn.edu.scnu.springbootcinema.mapper.ActorMapper;
import cn.edu.scnu.springbootcinema.mapper.MovieActorMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ActorService extends ServiceImpl<ActorMapper, Actor> {
    @Resource
    private ActorMapper actorMapper;
    @Resource
    private MovieActorMapper movieActorMapper;
    @Resource
    private RedisTemplate<String,List<Actor>> redisTemplate;
    public List<Actor> getActorsByMovieId(int movieId) {
        String redisKey = "movie:actors:" + movieId;
        List<Actor> actors = redisTemplate.opsForValue().get(redisKey);
        if (actors != null) {
            return actors;
        }
        QueryWrapper<MovieActor> movieActorQueryWrapper = new QueryWrapper<>();
        movieActorQueryWrapper.eq("movie_id", movieId);
        List<MovieActor> movieActors = movieActorMapper.selectList(movieActorQueryWrapper);
        actors = new ArrayList<>();
        for (MovieActor movieActor : movieActors) {
            Actor actor = actorMapper.selectById(movieActor.getActorId());
            actors.add(actor);
        }
        redisTemplate.opsForValue().set(redisKey,actors);
        return actors;
    }
}
